/*
 * @Description:
 * @Author: william
 * @Date: 2025-07-19 15:13:48
 * @LastEditors: william
 * @LastEditTime: 2025-09-22 15:26:10
 */
// 烹饪日志记录
// 烹饪过程记录也是用这个数据，烹饪完成就是烹饪日志记录
import { scheduler } from '@/utils/scheduler.js'

export const useCookingStore = defineStore(
  'cooking',
  () => {
    /**
     * 存储的是 cookItemInfo 对象列表
     */
    const cookingItemList = ref([])
    // 调料单位校准数据列表
    const flavourList = ref([])

    watch(
      () => cookingItemList.value,
      async (nv, ov) => {
        console.log('cookingItemList', nv, ov)
        // const { code } = await g_api.user.apiCheckNetwork()
        // if (code !== 200) return
        // // 烹饪日志上报
        // g_api.cooking.apiUploadRecipeCookRecord({
        //   recipeList: nv,
        //   showToast: false
        // })
      },
      {
        deep: true
      }
    )

    const startCookingScheduler = (time = 1000 * 10) => {
      // 增加烹饪记录数据上传任务
      scheduler.schedule(
        '烹饪记录数据上传定时任务',
        async () => {
          console.log('执行烹饪记录数据上传定时任务')
          const { code } = await g_api.user.apiCheckNetwork()
          if (code !== 200) return
          // 烹饪记录数据
          if (cookingItemList.value.length > 0) {
            g_api.cooking.apiUploadRecipeCookRecord({
              recipeList: cookingItemList.value,
              showToast: false
            })
          }
        },
        time
      ) // 每30分钟执行一次
    }
    

    const computedFlavourListMap = computed(() => {
      const map = new Map()
      flavourList.value.forEach(item => {
        map.set(item.model + item.flavourCode, item)
      })
      return map
    })

    /**
     * @description 计算校准后的 调料目标值
     * @param {*} ingredientCode 调料code
     * @param {*} deviceInfo 设备信息
     * @param {*} originalGoal 原始目标值
     * @returns 校准后的目标值
     */
    const getAnGoalByDeviceAndIngredient = (ingredientCode, deviceInfo, originalGoal) => {
      let goal = originalGoal * 1
      if (!ingredientCode || !originalGoal || !deviceInfo) return goal

      const { peripheralList, model } = deviceInfo
      const flavourItem = computedFlavourListMap.value.get(model + ingredientCode)
      if (!flavourItem) return goal
      
      const { baseCoefficient, adjustCoefficient, flavourCode } = flavourItem
      if (peripheralList && peripheralList.length) {
        const flavourPeripheral = peripheralList.find(
          peripheral => peripheral.ingredientCode === flavourCode)
        if (flavourPeripheral && flavourPeripheral.ratio) {
          goal = (originalGoal *  flavourPeripheral.ratio * baseCoefficient).toFixed(0) * 1
          console.log('ratio goal:',baseCoefficient, flavourPeripheral.ratio, goal)
          return goal
        }
      }
      goal = (originalGoal *  baseCoefficient * adjustCoefficient).toFixed(0) * 1
      console.log('base goal:',baseCoefficient, adjustCoefficient, goal)

      return goal
    }


    /**
     * 查询设备当前（最新）的烹饪记录
     * @param {string} deviceSn 设备SN号
     * @returns {deviceInfo} 烹饪信息，没有返回null
     */
    const getLatestCookInfoForDevice = deviceSn => {
      console.log(cookingItemList.value)

      const cookingItem = cookingItemList.value.filter(
        item => item.deviceSn === deviceSn
      )
      if (!cookingItem.length) return null

      // 取最新的记录即为当前烹饪中的记录
      return cookingItem.reduce((prev, cur) =>
        cur.createTime > prev.createTime ? cur : prev
      )
    }

    const downloadFlavourUnitAdjustInfo = async () => {
      const { data } = await g_api.cooking.apiDownloadFlavourUnitAdjustInfo({
        showToast: false
      })

      flavourList.value = data || []
     }

    return {
      cookingItemList,
      flavourList,
      computedFlavourListMap,
      getAnGoalByDeviceAndIngredient,
      getLatestCookInfoForDevice,
      downloadFlavourUnitAdjustInfo,
      startCookingScheduler
    }
  },
  {
    // persist: true // 配置持久化
    persist: [
      {
        key: 'cooking-store', // 自定义存储键名
        // storage: localStorage, // 默认是 localStorage,可以改为 sessionStorage,可全局配置
        pick: ['cookingItemList', 'flavourList'] // 只持久化指定的 state
      }
    ]
  }
)

export function useOutsideCookingStore() {
  return useCookingStore(g_store)
}
